import vue from '@vitejs/plugin-vue';
import fs from 'fs';
import { fileURLToPath, URL } from 'node:url';
import path from 'path';
import externalGlobals from "rollup-plugin-external-globals";
import ElementPlus from 'unplugin-element-plus/vite';
import { defineConfig } from 'vite';
import vueDevTools from 'vite-plugin-vue-devtools';
import pkg from './package.json' assert { type: 'json' };
import serverConfig from './server.config.js';

const { targetName, dependencies } = pkg;

// https://vite.dev/config/
export default ({ mode, ...opts }) => {
  return defineConfig({
    build: {
      manifest: true,
      rollupOptions: {
        output: {
          assetFileNames: targetName + '/assets/[name].[hash][extname]',
          chunkFileNames: targetName + '/js/[name].[hash].chunk.js',
          entryFileNames: targetName + '/js/[name].[hash].js',
        },
        plugins: [
          externalGlobals({
            'dayjs': 'dayjs',
            // 动态排除依赖库的打包
            ...getNpmDependencies(fileURLToPath(new URL('./', import.meta.url))),
          }),
        ],
      },
      lib: {
        name: 'Sample', // 库的名称
        entry: 'src/main.js', // 入口文件
        formats: ['umd'], // 打包的格式
      },
    },
    plugins: [
      vue(),
      vueDevTools(),
      ElementPlus(),
    ],
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url))
      },
    },
    server: {
      proxy: {
        '^/(api|MP|Base|entrypoints)': {
          target: serverConfig.host || 'http://localhost:5000',
          secure: false,
          changeOrigin: true, // 修改请求头中的 Origin
        },
      },
    },
  });
};

function getNpmDependencies(appPath) {
  const depts = {};
  // npm依赖
  if (dependencies) {
    try {
      Object.keys(dependencies).forEach(packageName => {
        const txt = fs.readFileSync(path.join(appPath, 'node_modules', packageName, 'package.json'), { encoding: "utf-8" });
        const { name, targetName } = JSON.parse(txt);
        if (name && targetName) {
          depts[name] = targetName;
        }
      });
    } catch (e) {
      if (e.code !== 'ENOENT') throw e;
    }
  }
  return depts;
}